import java.io.*;

/**
 * UserReader gets initialized with a PrintWriter (in this case a 
 * {@link ThreadSafeWriter} created with the output stream of a Socket object) 
 * then runs in its own thread copying data from standard input to the output 
 * stream
 *
 * @author David Gardner
 */
public class UserReader extends Thread {
  private PrintWriter out = null;
  private DataInputStream stdIn;
  private volatile boolean bDone = false;

 /**
   * @param outWriter   A PrintWriter object where user date from the Standard
  *                     in should be copied to
   */
  UserReader (PrintWriter outWriter) {
    out = outWriter;
    stdIn = new DataInputStream (System.in);		
  }

 /**
  * Copies data retrieved from standard in to the PrintWriter object UserReader 
  * was initialized with
  */
  public void run () {
    while (!bDone) { 
      try {
        if (stdIn.available() > 0) { //don't block
          out.write (stdIn.read ());
          if (out.checkError ())
              bDone = true; //something bad happened so just quit
        }
      } catch (IOException error) { 
          bDone = true;
          System.err.println("Error");
      }
    }
  }
 
 /**
  * Alerts UserReader to shutdown.
  */
  public void close () {
    bDone = true;
  }
}
